<template>
  <design-dialog
      wrapClassName="dialog-images-manager"
      :title="title"
      :visible="visible"
      :width="960"
      @isOk="handle_confirm"
      @isCancel="handle_cancel">

    <!-- dialog-body -->
    <div style="height:50vh;overflow:auto">
			<div style="display: flex;">
				<template v-if="this.config.choose == 'article'">
					<!-- 文章营销 -->
					<a-dropdown>
						<a-menu slot="overlay" @click="selectArticleType">
							<a-menu-item v-for="(item,index) in article_type_list" :key="index">{{item.name}}</a-menu-item>
						</a-menu>
						<a-button style="margin-right: 8px"> {{select_article_type.name}} <a-icon type="down" /> </a-button>
					</a-dropdown>
					<a-dropdown>
						<a-menu slot="overlay" @click="selectArticleCategory">
							<a-menu-item v-for="(item,index) in article_category" :key="index">{{item.name}}</a-menu-item>
						</a-menu>
						<a-button style="margin-right: 8px"> {{select_article_category.name||'全部'}} <a-icon type="down" /> </a-button>
					</a-dropdown>
				</template>
				<template v-if="showSearch">
					<a-input style="width: 85%;margin-bottom: 10px;margin-right: 10px" v-model.trim="keywords" placeholder="请输入关键字搜索">
					</a-input>
					<a-button style="width:90px;" type="primary" @click.stop="currentChange(1)">搜索</a-button>
				</template>
				</div>
      <div>
        <a-table
            :row-selection="{ selectedRowKeys: selectedRowKeys, onSelect: onSelectChange, onSelectAll:onSelectAll }"
            :columns="columns" :rowKey="idText"
            :data-source="main_page_list"
            :pagination="false"
        >
          <div slot="cps_img" class="goods_img" slot-scope="text, record">
            <img :src="record.logo"/>
          </div>
          <div slot="image" class="goods_img" slot-scope="text, record">
            <img v-if="record.image" :src="record.image"/>
          </div>
          <span slot="plugins_names" slot-scope="text, record">
            <span>{{record.plugins_names}}</span>
          </span>
          <span slot="enough" class="edit-box" slot-scope="text, record">
            <span class="tag" v-if="record.enough == 0">无门槛</span><br v-if="record.enough == 0"/>
            <span class="tag" style="background-color: #1e6abc" v-if="record.enough != 0">满{{record.enough}}可用</span><br v-if="record.enough != 0" />
            <span>{{record.coupon_method == 1?`立减${record.deduct}`:`打${record.discount}折`}}</span>
          </span>
          <span slot="usetotal" class="edit-box" slot-scope="text, record">
            <span>{{record.usetotal}} / {{record.gettotal}} / {{record.lasttotal}}</span>
          </span>
          <div slot="service_name" class="service_img" slot-scope="text, record">
            <img v-if="record.avatar" :src="record.avatar"/>
            <span>{{record.name}}</span>
          </div>
          <div slot="service_member_nickname" class="service_img" slot-scope="text, record">
            <img v-if="record.member_avatar" :src="record.member_avatar"/>
            <span>{{record.member_nickname}}</span>
          </div>
					<div slot="is_show" slot-scope="text, record">
            {{Number(record.is_show) ==1?'显示':'不显示'}}
          </div>
        </a-table>
      </div>
    </div>

    <div style="position: absolute;bottom: 80px;left: 50%;transform: translateX(-50%);">
      <a-pagination
          style="margin-top: 15px;text-align: center"
          showQuickJumper
          :pageSize="main_page_pagination.pageSize"
          :current="main_page_pagination.current"
          :total="main_page_pagination.total"
          @change="currentChange"/>
    </div>

  </design-dialog>
</template>

<script>
	const article_type_list = [
		{
			type: '-1',
			name: '全部'
		},
		{
			type: '0',
			name: '普通文章'
		},
		{
			type: '1',
			name: '音频文章'
		}
	]
	const article_columns = [
		{
			title: 'ID',
			dataIndex: 'id',
		},
		// {
		// 	title: '文章图片',
		// 	dataIndex: 'thumb',
		// 	width: 100,
		// 	scopedSlots: {customRender: 'thumb'}
		// },
		{
			title: '文章标题',
			dataIndex: 'title',
		},
		{
			title: '文章作者',
			dataIndex: 'author',
		},
		{
			title: '文章分类',
			dataIndex: 'category_name',
		},
		{
			title: '文章创建时间',
			dataIndex: 'created_at',
		},
	];

	const article_class_columns = [
		{
			title: 'ID',
			dataIndex: 'id',
			width: 120,
		},
		{
			title: '文章分类标题',
			dataIndex: 'name',
		},
	];

	const community_columns = [
		{
			title: 'ID',
			dataIndex: 'id',
		},
		{
			title: '帖子标题',
			dataIndex: 'title',
		},
		{
			title: '帖子作者',
			dataIndex: 'user_nickname',
		},
		{
			title: '帖子首图',
			dataIndex: 'image',
			scopedSlots: { customRender: 'image' },
		},
	];

	const coupons_columns = [
		{
			title: 'ID',
			dataIndex: 'id',
		},
		{
			title: '来源',
			dataIndex: 'plugins_names',
			scopedSlots: { customRender: 'plugins_names' },
		},
		{
			title: '优惠券名称',
			dataIndex: 'name',
		},
		{
			title: '使用条件 / 优惠',
			dataIndex: 'enough',
			scopedSlots: { customRender: 'enough' },
		},
		{
			title: '已使用 / 已发出 / 剩余数量',
			dataIndex: 'usetotal',
			scopedSlots: { customRender: 'usetotal' },
		},
		{
			title: '创建时间',
			dataIndex: 'created_at',
		},
	];

	const video_columns = [
		{
			title: 'ID',
			dataIndex: 'id',
		},
		{
			title: '标题',
			dataIndex: 'title',
		},
		{
			title: '作者',
			dataIndex: 'member_nickname',
		},
		{
			title: '视频发布时间',
			dataIndex: 'created_at',
		},
	];
	const video_columns_category = [
		{
			title: '分类ID',
			dataIndex: 'id',
		},
		{
			title: '分类名称',
			dataIndex: 'name',
		},
		{
			title: '是否显示',
			dataIndex: 'is_show',
			scopedSlots: { customRender: 'is_show' },
		}
	];
	

	const service_columns = [
		{
			title: 'ID',
			dataIndex: 'id',
			width: 100,
		},
		{
			title: '客服',
			dataIndex: 'name',
			align: 'center',
			width: 250,
			scopedSlots: { customRender: 'service_name' },
		},
		{
			title: '会员',
			dataIndex: 'member_nickname',
			align: 'center',
      width: 250,
			scopedSlots: { customRender: 'service_member_nickname' },
		},
		{
			title: '企业名称',
			dataIndex: 'crop_name',
		},
	];

	const cps_columns = [
		{title: '商品ID', align: 'center', dataIndex: 'goods_id', },
		{title: '第三方ID', align: 'center', dataIndex: 'b_id',},
		{
			title: '商品logo',
			align: 'center',
			dataIndex: 'logo',
			scopedSlots: {customRender: 'cps_img'}
		},
		{title: '商品名', align: 'center', dataIndex: 'name', width: 350,},
	];

	const courseSupply_columns = [
		{title: 'ID', align: 'center', dataIndex: 'id', },
		{title: '课程名称', align: 'center', dataIndex: 'title',},
		{title: '讲师', align: 'center', dataIndex: 'lecturer_name',},
		{title: '价格', align: 'center', dataIndex: 'price'},
		{title: '上架状态', align: 'center', dataIndex: 'status_name'},
	];
	export default {
		name: 'choose-list',

		props: {
			value: {
				type: Array,
				default: []
			},
			// 配置项
			config: {
				type: Object,
				required: true,
			},
			// 根配置
			rootConfig: {
				type: Object,
				required: true
			}
		},
		data() {
			return {
				article_category: [],//文章营销分类
				select_article_category: {},
				article_type_list: article_type_list,//文章营销类型
				select_article_type: article_type_list[0],//文章营销选择的类型，默认全部
				article_columns,
				article_class_columns,

				community_columns,
				coupons_columns,
				video_columns,
				service_columns,
				cps_columns,
				selectedRowKeys: [],
				selectedRows: [],
				idText: 'id',

				keywords: '',
				visible: false,
				url: '',
				// 主页列表
				main_page_list: [],
				// 主分页的页码
				main_page_pagination: {
					current: 1,
					pageSize: 20,
					total: 0
				},
				showSearch: true//是否显示搜索框
			};
		},
		mounted() {
			if(this.config.choose === 'cps_brand') {
				this.idText = 'goods_id'
			}
			if(this.config.choose === 'article') {
				this.getArticleCategory();
			}
		},
		watch: {
			value(newVal) {
				// this.selectedRows = newVal;
			},
		},
		computed: {
			columns() {
				this.showSearch = true;
				switch(this.config.choose) {
					case 'coupons':
						return coupons_columns;
					case 'article':
						if(this.rootConfig.get_style && this.rootConfig.get_style.value == 3) {
							// 判断是分类
							return article_class_columns;
						}else {
							return article_columns;
            }
					case 'community':
						return community_columns;
					case 'video':
						if(this.rootConfig.get_style && this.rootConfig.get_style.value == 2) {
							this.showSearch = false;
							return video_columns;//手动选择
						} else if(this.rootConfig.get_style && this.rootConfig.get_style.value == 3) {
							return video_columns_category;//选择分类
						}
					case 'service':
						return service_columns;
					case 'cps_brand':
						return cps_columns;
					case 'courseSupply':
						return courseSupply_columns;
					default:
						return article_columns;
				}
      },
			title() {
				switch(this.config.choose) {
					case 'coupons':
						return '选择优惠券';
					case 'article':
						return '选择文章';
					case 'community':
						return '选择帖子';
					case 'video':
						return '选择短视频';
					case 'service':
						return '选择客服';
					case 'cps_brand':
						return '选择品牌券';
					case 'courseSupply':
						return '选择课程';
					default:
						return '选择文章';
				}
      }
		},
		methods: {
			/**
			 * 分页切换
			 */
			currentChange(page) {
				this.main_page_pagination.current = page;
				let json = {};
				if(this.config.choose === 'article') {
					this.url = 'plugin.decorate.admin.decorate-common.search-article';
					if(this.rootConfig.get_style && this.rootConfig.get_style.value == 3) {
						// 判断是分类
						this.url = 'plugin.decorate.admin.decorate-common.get-article-cat';
						json = {
							page: page,
							name: this.keywords
						};
					}else {
						json = {
							page: page,
							title: this.keywords
						};
						if(this.rootConfig.get_style && this.rootConfig.get_style.value == 2) {
							// 判断是否选择了文章类型（音频/普通文章），是否选择按分类搜索
							if(this.select_article_category.id != '-1') json.category_id = this.select_article_category.id;
							if(this.select_article_type.type != '-1') json.type = this.select_article_type.type;
						}
          }
				}else if(this.config.choose === 'community') {
					this.url = 'plugin.store-decorate.admin.decorate-common.get-communities-list';
					json = {
						page: page,
						// title: this.keywords
					};
				}else if(this.config.choose === 'coupons') {
					this.url = 'plugin.decorate.admin.decorate-common.search-coupon';
					json = {
						page: page,
						coupon_name: this.keywords
					};
					if(this.fun.getKey('store_id') && window.location.href.indexOf('store_design') > -1) {
						// 门店装修
						this.url = 'plugin.store-decorate.admin.decorate-common.search-coupon';
						json.store_id = this.fun.getKey('store_id');
					}
				}else if(this.config.choose === 'video') {
					this.url = this.rootConfig.get_style.value == 2?'plugin.decorate.admin.decorate-common.search-video-share':'plugin.decorate.admin.decorate-common.search-video-share-category';
					json = {
						page: page,
						keyword: this.keywords
					};
				}else if(this.config.choose === 'service') {
					this.url = 'plugin.decorate.admin.decorate-common.search-group-chat-employees';
					json = {
						page: page,
						title: this.keywords
					};
				}else if(this.config.choose === 'cps_brand') {
					this.url = 'plugin.aggregation-cps.admin.equity-goods.searchBrandGoods';
					json = {
						page: page,
						divide_page: 1,
						keyword: this.keywords
					};
				} else if(this.config.choose === 'courseSupply') {
					this.url = 'plugin.decorate.admin.decorate-common.search-course-supply';
					json = {
						page: page,
						keyword: this.keywords
					};
				}
				$http
						.post(this.url,json,"loading")
						.then(response => {
							if (response.result === 1) {
								this.main_page_pagination.total = response.data.total;
								this.main_page_pagination.pageSize = response.data.per_page;
								this.main_page_list = response.data.data;
							} else {
								this.main_page_list = [];
								if (response.data.status === -1) {
									this.currentChange(1);
								}
								// this.$message.error(response.msg);
							}
						})
						.catch(err => {
							console.error(err);
						});
			},
			onSelectChange(record, selected, selectedRows) {
				if(selected) {
          this.selectedRowKeys.push(record[this.idText]);
					this.selectedRows.push(record);
				}else {
          this.selectedRowKeys= this.selectedRowKeys.filter((item)=> {
            return item != record[this.idText]
          });
          this.selectedRows = this.selectedRows.filter((item)=> {
            return item[this.idText] != record[this.idText]
          });
				}

				// console.log('selectedRowKeys changed: ', this.selectedRowKeys, this.selectedRows);
			},

			onSelectAll(selected, selectedRows, changeRows) {
				if(selected) {
					this.selectedRows.push(...changeRows);
					changeRows.map((item) => {
            this.selectedRowKeys.push(item[this.idText])
					});
				}else {
					changeRows.map((record) => {
            this.selectedRowKeys= this.selectedRowKeys.filter((item)=> {
              return item != record[this.idText]
            });
            this.selectedRows = this.selectedRows.filter((item)=> {
              return item[this.idText] != record[this.idText]
            });
					});
				}

				// console.log(selected, selectedRows, changeRows);
			},

			unique (arr) {
				return Array.from(new Set(arr))
			},

			show (list) {
				this.currentChange(1);
				this.selectedRowKeys = [];
				list.forEach((item)=>{
          this.selectedRowKeys.push(item[this.idText])
        });
				this.selectedRows = JSON.parse(JSON.stringify(list));
				this.visible = true;
			},
			/**
			 * 弹窗按钮 - 确认
			 */
			handle_confirm () {
				this.$emit('confirm', this.unique(this.selectedRows));
				this.visible = false;
			},

			/**
			 * 弹窗按钮 - 取消
			 */
			handle_cancel () {
				this.visible = false;
			},

			selectArticleType(e){
				this.select_article_type = this.article_type_list[e.key];
				this.currentChange(1);
			},
			selectArticleCategory(e){
				this.select_article_category = this.article_category[e.key];
				this.currentChange(1);
			},
			getArticleCategory(){
				if(this.article_category.length != 0) return; 
				$http
						.post('plugin.decorate.admin.decorate-common.articleCategory',{},"loading")
						.then(response => {
							if (response.result === 1) {
								this.article_category = [{name: "全部", id: -1}];
								this.article_category = this.article_category.concat(response.data);
							} else {
								// this.$message.error(response.msg);
							}
						})
						.catch(err => {
							console.error(err);
						});
			}
		},
	};
</script>

<style lang="less" scoped>
  .link-box {
    margin: 10px 10px;
    .title {
      position: relative;
      font-weight: bold;
      margin-left: 10px;
      color: #29ba9c;
    }
    .title::before {
      content: "";
      width: 5px;
      height: 25px;
      position: absolute;
      top: 0;
      left: -10px;
      background: #29ba9c;
    }
    .links {
      margin-left: 15px;
      display: flex;
      flex-wrap: wrap;
      span {
        cursor: pointer;
        margin: 10px 0 0 20px;
      }
      span.active {
        color: #29ba9c;
      }
    }
  }

  .search-result {
    margin-top: 20px;
  }

  .goods_img {
    height: 60px;
    line-height: 60px;

    & > img {
      width: auto;
      height: auto;
      max-height: 100%;
      max-width: 100%;
    }
  }

  .service_img {
    display: flex;
    flex-direction: column;

    & > img {
      width: auto;
      height: auto;
      max-height: 40px;
      max-width: 40px;
      margin: 5px auto;
    }
  }

  .edit-box {
    display: inline-block;
    text-align: center;
    .tag {
      background-color: #29ba9c;
      color: white;
      padding: 2px 5px;
      border-radius: 5px;
    }
  }
</style>
